package org.finesys.commom.jackson.config;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import org.finesys.commom.jackson.module.JavaLongTypeModule;
import org.finesys.commom.jackson.module.JavaTimeModule;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.time.ZoneId;
import java.util.Locale;
import java.util.TimeZone;

@AutoConfiguration
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return jacksonObjectMapperBuilder -> {
            // 区域处理
            jacksonObjectMapperBuilder.locale(Locale.CHINA);
            jacksonObjectMapperBuilder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
            // 日期格式
            jacksonObjectMapperBuilder.simpleDateFormat(DatePattern.NORM_DATE_PATTERN);
            // Long转String
            jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
            jacksonObjectMapperBuilder.modules(new JavaTimeModule(), new Jdk8Module(), new JavaLongTypeModule(), new SimpleModule());
            // 序列化和反序列化对象中的所有字段并忽略它们的可见性修饰符
            jacksonObjectMapperBuilder.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            // featuresToDisable
            jacksonObjectMapperBuilder.featuresToDisable(
                    // 不将日期写为时间戳
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    // 忽略未知属性
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                    // 对象属性为空时可以序列化
                    SerializationFeature.FAIL_ON_EMPTY_BEANS);
        };
    }
}
